package Q5;

import java.io.*;
import java.net.Socket;

public class ClientTool {
    //从服务器下载文件
    public static void recieveFileFromServer (Socket socket, File file){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //初始化输入输出流
            bis = new BufferedInputStream(socket.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(file));
            byte[] arr = new byte[2048];
            int res = 0;
            while((res = bis.read(arr)) > 0) {
                bos.write(arr, 0, res);
                bos.flush();
                if(res < 2048) {
                    break;
                }
            }
            System.out.println("文件" + file.getName() + "已保存");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //发送文件到服务器
    public static void sendFile(File file, Socket socket) {
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(socket.getOutputStream());

            byte[] arr = new byte[2048];
            int res = 0;
            while((res = bis.read(arr)) > 0) {
                bos.write(arr, 0, res);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //创建用户的存储目录


    public static void createLocalStorage(String username) {
        File file = new File("D:/Talk/client/" + username);
        if (file.exists()) {
            System.out.println("用户存储目录已存在");
        } else {
            System.out.println("目录创建成功" + file.getPath());
        }
    }
}
